package com.tz.platform.page;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tz.platform.utils.StringUtil;

public class PageCondition implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private int pageSize; // 每页数量
	private int pageIndex; // 当前页
	private Integer pageNo; // 当前页号

	private Integer allCount; // 总记录条数
	private Integer pageCount; // 总页数

	private List<?> list = new ArrayList<Object>(); // 当页的记录
	
	@SuppressWarnings("unused")
	private boolean isLastPage;
	@SuppressWarnings("unused")
	private boolean isFirstPage;
	@SuppressWarnings("unused")
	private boolean hasPrevPage;
	@SuppressWarnings("unused")
	private boolean hasNextPage;
	
	private static final String lt="lt";
	private static final String lteq="lteq";
	private static final String gt="gt";
	private static final String gteq="gteq";
	private static final String eq="eq";
	private String queryMark; // 查询条件 操作符
	private String goalsStr; // 查询条件  目标属性
	private String queryString; // 查询条件 用于拼接SQL
	private String sortBys;
	private Map<String, Object> paramsCondition = new HashMap<String, Object>(); // 查询条件
	private Map<String, String> options = new HashMap<String, String>(); // 操作符号
	private Map<String, String> goals = new HashMap<String, String>(); // 目标属性
	private Map<String, String> listSort = new HashMap<String, String>(); // 排序字段

	public PageCondition() {
		// 设置默认页面数量为10；
		// pageSize=pageSize==0?10:pageSize;
		// 设置默认当前页为1；
		// pageIndex=pageIndex==0?1:pageIndex;

		this.allCount = 0;
		this.pageCount = 0;
		this.pageNo = 1;
		this.pageSize = 10;
		;
	}

	public Map<String, Object> getParamsCondition() {
		return paramsCondition;
	}

	public void setParamsCondition(Map<String, Object> paramsCondition) {
		this.paramsCondition = paramsCondition;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	public void setQueryString(String queryString){
		this.queryString = queryString;
		//设置查询条件
		paramsCondition =  jqStringToMap(queryString);
	}
	
	// 拼接查询条件
	public String getQueryString() {
		updateOptions();
		StringBuffer sb = new StringBuffer();
		if (paramsCondition == null || paramsCondition.size()==0) {
			return null;
		}
		for (Map.Entry<String, Object> entry : paramsCondition.entrySet()) {
			if (!StringUtil.msIsEmpty(entry.getValue())){
				if(entry.getValue() instanceof String){
					if (!"%".equals(entry.getValue())
							&& !"%%".equals(entry.getValue())
							&& !"%null".equalsIgnoreCase((String) entry.getValue())
							&& !"null%".equalsIgnoreCase((String) entry.getValue())
							&& !"%null%".equalsIgnoreCase((String) entry.getValue())) {
						String key=entry.getKey();
						String goalKey=entry.getKey();
						if(goals.get(goalKey)!=null&&!goals.get(goalKey).isEmpty()){
							goalKey=goals.get(goalKey);
						}
						if (!StringUtil.msIsEmpty((String) options.get(key))) {
							if (options.get(key).equals("like")) {
								sb.append(" and " + goalKey + "%" + options.get(key) + "%:"+key+" ");
							} else {
								if(goalKey.equals("upOrderId")){
									if(paramsCondition.get(key).equals("isnull")){
										sb.append(" and (upOrderId=null or upOrderId='') ");
									}else if(paramsCondition.get(key).equals("notnull")){
										sb.append(" and (upOrderId is not null) and upOrderId<>'' ");
									}
								}else{
									sb.append(" and " + goalKey + options.get(key) + ":"+key+" ");
								}
							}
						} else {
							sb.append(" and " + goalKey + "=:"+key+" ");
						}
					}
				}else{
					String key=entry.getKey();
					String goalKey=entry.getKey();
					if(goals.get(goalKey)!=null&&!goals.get(goalKey).isEmpty()){
						goalKey=goals.get(goalKey);
					}
					if (!StringUtil.msIsEmpty((String) options.get(key))) {
						sb.append(" and " + goalKey + options.get(key) + ":"+key+" ");
					} else {
						sb.append(" and " + goalKey + "=:"+key+" ");
					}
				}
			}
		}
		String str = sb.toString();
		if (str.length() > 4) {
			this.queryString = str.substring(4, str.length());
		}else{
			queryString = "";
		}
		return queryString;
	}

	/**
	 * 设置查询条件
	 * 
	 * @param key
	 * @param value
	 */
	public void updateConditions(String key, String option, Object value) {
		// 放入更新条件
		paramsCondition.put(key, value);
		// 放入操作符号
		options.put(key, option);
	}

	// 设置排序条件
	public void setSortBys(String key, String value) {
		listSort.put(key, value);
	}

	// 拼接排序条件
	public String getSortBys() {
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> entry : listSort.entrySet()) {
			if (!StringUtil.msIsEmpty(entry.getKey())
					&& !StringUtil.msIsEmpty(entry.getValue())) {
				sb.append(entry.getKey() + " " + entry.getValue() + ",");
			}
		}
		if (sb.toString().trim().length() > 0) {
			this.sortBys = " order by "
					+ sb.toString().substring(0, sb.toString().length() - 1);
		}
		return sortBys;
	}

	public static void main(String[] args) {
		PageCondition condition = new PageCondition();
		condition.setSortBys("af", "desc");
		String str = condition.getSortBys();
		System.out.println("sort :" + str);
	}

	public Integer getPageNo() {
		return !StringUtil.msIsEmpty(pageNo) ? pageNo : 1;
	}

	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}

	public Integer getAllCount() {
		return allCount;
	}

	public void setAllCount(Integer allCount) {
		if (allCount.intValue() > 0) {
			this.allCount = allCount;
			int count = allCount / getPageSize();
			if (allCount % getPageSize() > 0)
				count++;
			setPageCount(count);
		} else {
			this.allCount = 0;
			this.pageCount = 0;
		}
	}

	public Integer getPageCount() {
		return pageCount;
	}

	public void setPageCount(Integer pageCount) {
		this.pageCount = pageCount;
	}

	public boolean getHasNextPage() {
		//return (this.pageCount > 1) && (this.getPageNo() < this.pageCount);
		return list.size()==pageSize;
	}

	public boolean getHasPrevPage() {
		return this.getPageNo() > 1;
	}

	public boolean getIsFirstPage() {
		return (this.getPageNo() <= 1) && (this.pageCount >= 1)
				|| this.pageCount == 0;
	}

	public boolean getIsLastPage() {
		return (this.getPageNo().equals(this.pageCount))
				&& (this.pageCount >= 1) || this.pageCount == 0;
	}

	public List<?> getList() {
		return list;
	}

	public void setList(List<?> list) {
		this.list = list;
	}

	public int getPageIndex() {
		return pageIndex;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}
	
	
	private HashMap<String,Object> jqStringToMap(String jqString)
	  {
	    HashMap<String,Object> hashMap =  new HashMap<String,Object>();
	    if( StringUtil.msIsEmpty(jqString) ) {
	    	return hashMap;
	    }
	    
	    String strSepChar = "&";
	    String strEqlChar = "=";
	    // AntiXSSSimple 转义后，会从servletRequest的parameter中获取queryString，并将其中的“&”和“=”替换成“&#38;”和“&#61;”
	    // 并且通过setAttribute的方式放入servletRequest中。如果后台controller的方法中，不包含ServletRequest或者HttpServletRequest类型的参数，
	    // 则PageList中的queryString是从attribute中获取到的被转移过的字符串。如果包含ServletRequest或者HttpServletRequest类型的参数，则
	    // PageList中的queryString是从parameter中获取到的为经过转移的字符串，所以这里有两种拆分方式
//	    if( jqString.indexOf( "&#38;" )!=-1 || jqString.indexOf( "&#61;" )!=-1){
//	      strSepChar = "&#38;";
//	      strEqlChar = "&#61;";
//	    }
	    
	    //拆分传入参数。例如/darcy2/wellName=sdf&/darcy2/wellFTP=2323
	    String strParamName,strParamValue;
	    String[] strAllParams = jqString.split( strSepChar );
	    String[] strKeyValues;
	    for(String strParam:strAllParams)
	    {
	      strKeyValues = strParam.split( strEqlChar );
	      if(strKeyValues.length<2) continue;// 该参数没有传值过来
	      strParamName = strKeyValues[0];
	      strParamValue = strKeyValues[1];
	      strParamValue = strParamValue.replaceAll("%5B", "[");
	      strParamValue = strParamValue.replaceAll("%5D", "]");
	      strParamValue = strParamValue.replaceAll("\\+", " ");// 去空格。前台页面提交时，使用jquery.serialize方法，空格被转为+，真正的+被转换为%2B
	      strParamValue = strParamValue.replaceAll("%2C", ",");
	      if(!StringUtil.msIsEmpty(strParamValue.trim()))
	      {
	        hashMap.put( strParamName, strParamValue );
	      }
	    }
	    return hashMap;
	  }

	public String getQueryMark() {
		return queryMark;
	}

	public void setQueryMark(String queryMark) {
		this.queryMark = queryMark;
	}
	
	private void updateOptions(){
		String jqString=getQueryMark();
		if(jqString!=null&&!jqString.isEmpty()){
			String[] marks=jqString.split("&");
			String[] keyValue;
			String key,value=null;
			for(String mark:marks){
				keyValue=mark.split("=");
				if(keyValue!=null&&keyValue.length==2){
					key=keyValue[0];
					value=keyValue[1];
					if(value.equals("*%")){
						updateConditions(key, "like", paramsCondition.get(key) + "%");
					}else if(value.equals("%*")){
						updateConditions(key, "like", "%"+paramsCondition.get(key));
					}else if(value.equals("%*%")){
						updateConditions(key, "like", "%"+paramsCondition.get(key) + "%");
					}else if(value.equals(lt)){
						options.put(key, "<");
					}else if(value.equals(lteq)){
						options.put(key, "<=");
					}else if(value.equals(gt)){
						options.put(key, ">");
					}else if(value.equals(gteq)){
						options.put(key, ">=");
					}else if(value.equals(eq)){
						options.put(key, "=");
					}
				}
			}
		}
	}

	public String getGoalsStr() {
		return goalsStr;
	}

	public void setGoalsStr(String goalsStr) {
		this.goalsStr = goalsStr;
		if(goalsStr!=null&&!goalsStr.isEmpty()){
			String[] goalsString=goalsStr.split("&");
			String[] keyValue;
			String key,value=null;
			for(String mark:goalsString){
				keyValue=mark.split("=");
				if(keyValue!=null&&keyValue.length==2){
					key=keyValue[0];
					value=keyValue[1];
					goals.put(key, value);
				}
			}
		}
	}

}
